package edu.university.demo.core.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import edu.university.demo.common.ShiroUser;
import edu.university.demo.system.entit.User;
import edu.university.demo.system.service.AccountService;

public class ShiroDbRealm extends AuthorizingRealm {

	@Autowired
	protected AccountService accountService;
	
	@Autowired
	private ShiroFactroy shiroFactory;

	/**
	 * 认证回调函数,登录时调用.
	 * 
	 * @author mayanping
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		
		User user = shiroFactory.user(token.getUsername());
		ShiroUser shiroUser = shiroFactory.shiroUser(user);
		SimpleAuthenticationInfo info = shiroFactory.info(shiroUser, user, getName());
		
		return info;
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		User user = accountService.getUser(shiroUser.getId());
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRole(user.getRoles());
		return info;
	}
}
